<?php namespace Asset;

use Illuminate\Console\Command;

/**
 * The WatchCommand class is a step up from the BuildCommand class in that it processes asset files similarly.
 */
class WatchCommand extends Command {
	
	/**
	 * The console command name.
	 *
	 * @var string
	 */
    protected $name = 'watch';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Watches resource files for changes.';
    
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
    	parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $watcher  = \App::make('watcher');
        $sections = \Config::get('asset');

        foreach ($sections as $section => $assets) {
            foreach ($assets as $output => $input) {
            	
            	// Is local, no process
                if (!is_string($output)) {
                    continue;
                }

                // Ensure $input is array
                if (!is_array($input)) {
                    $input = [$input];
                }

                foreach ($input as $file) {
                	// Create a listener for a given resource
                    $listener = $watcher->watch($this->getPath() . '/' . $file);

                    $listener->onModify(function() use ($section, $output, $input, $file) {

                        $options = [
                            '--output' => $output,
                            'input' => join(',', $input)
                        ];

                        $this->line('<info>Rebuilding</info> <comment>' . $output . '</comment> <info>after change to</info> <comment>' . $file . '</comment>');

                        if (ends_with($output, '.min.css')) {
                            $options['type'] = 'css';
                            $this->call('asset:minify', $options);
                        } else if (ends_with($output, '.min.js')) {
                            $options['type'] = 'js';
                            $this->call('asset:minify', $options);
                       	} else {
                            $this->call('asset:combine'', $options);
                        }

                    });
                }
            }
        }

        $watcher->startWatch();
    }

    protected function getPath()
    {
        return public_path();
    }
}